package com.thiswhyme.mail.service;

import com.thiswhyme.common.expection.BusinessException;
import com.thiswhyme.mail.config.EmailProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @description: 邮件发送器抽象类
 * @author: thiswhyme
 * @date: 2021/5/7
 */
public abstract class AbstractEmailSender implements EmailSender {

    @Autowired
    private EmailProperties emailProperties;

    /**
     * 获取默认邮件配置
     * @param key 默认配置对应的key
     * @return
     */
    public EmailProperties.EmailProperty getDefaultEmailProperty(String key) {
        Map<String, EmailProperties.EmailProperty> properties = emailProperties.getProperties();
        return properties == null ? null : properties.get(key);
    }

    /**
     * 获取并校验邮件配置
     * @param property 传入配置
     * @param key 默认配置对应的key
     * @return
     */
    public EmailProperties.EmailProperty getAndCheckEmailProperty(EmailProperties.EmailProperty property, String key) {
        EmailProperties.EmailProperty result;
        EmailProperties.EmailProperty defaultProperty = getDefaultEmailProperty(key);
        if (null == property && null == defaultProperty) {
            throw new BusinessException("邮件配置为空");
        } else if (null != property && null != defaultProperty) {
            result = new EmailProperties.EmailProperty();
            result.setFrom(StringUtils.isEmpty(property.getFrom()) ? defaultProperty.getFrom() : property.getFrom());
            result.setTo(CollectionUtils.isEmpty(property.getTo()) ? defaultProperty.getTo() : property.getTo());
            result.setSubject(StringUtils.isEmpty(property.getSubject()) ? defaultProperty.getSubject() : property.getSubject());
            result.setCc(CollectionUtils.isEmpty(property.getCc()) ? defaultProperty.getCc() : property.getCc());
            if (StringUtils.isEmpty(result.getFrom()) || CollectionUtils.isEmpty(result.getTo()) || StringUtils.isEmpty(result.getSubject())) {
                throw  new BusinessException("邮件配置不完整");
            }
        } else {
            result = property == null ? defaultProperty : property;
        }
        return result;
    }
}
